package com.jz.community.moduleshopping.confirmOrder.ui;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.view.RxView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.baseGoods.GoodInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopListInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.NumberArithmeticUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToCartRefreshEvent;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.address.bean.BaseAddressInfo;
import com.jz.community.moduleshopping.address.bean.UserAddressInfo;
import com.jz.community.moduleshopping.address.task.GetAddressListTask;
import com.jz.community.moduleshopping.address.task.GetShopDistributionTask;
import com.jz.community.moduleshopping.address.ui.AddAddressActivity;
import com.jz.community.moduleshopping.address.ui.ReceivingAddressListActivity;
import com.jz.community.moduleshopping.confirmOrder.adapter.ConfirmGoodsListAdapter;
import com.jz.community.moduleshopping.confirmOrder.bean.BaseOrderCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderPostageInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.ShopSelfAddressInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.SubmitOrderResultBean;
import com.jz.community.moduleshopping.confirmOrder.enums.OrderPayFormType;
import com.jz.community.moduleshopping.confirmOrder.payPop.NewCommPayPopUp;
import com.jz.community.moduleshopping.confirmOrder.presenter.NewConfirmPresenter;
import com.jz.community.moduleshopping.confirmOrder.task.GetShopSelfAddressTask;
import com.jz.community.moduleshopping.confirmOrder.ui.view.ShopSendPriceControl;
import com.jz.community.moduleshopping.confirmOrder.util.OrderRequestConstant;
import com.jz.community.moduleshopping.shopCart.bean.SendTypeEnum;
import com.jz.community.moduleshopping.utils.SpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony.Fan on 2018/4/19 17:24
 * <p>
 * 确认订单
 */
@Route(path = RouterIntentConstant.MODULE_SHOPPING_CONFIRM_ORDER)
public class NewConfirmOrderActivity extends BaseMvpActivity<NewConfirmOrderView.View, NewConfirmPresenter> implements NewConfirmOrderView.View {
    @BindView(R2.id.tv_back)
    ImageView tvBack;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.commit_order_toolbar)
    Toolbar commitOrderToolbar;
    @BindView(R2.id.tv_consignee_name)
    TextView tvConsigneeName;
    @BindView(R2.id.tv_consignee_phone)
    TextView tvConsigneePhone;
    @BindView(R2.id.iv_address_type)
    ImageView ivAddressType;
    @BindView(R2.id.tv_recommend_post)
    TextView tvRecommendPost;
    @BindView(R2.id.tv_consignee_address)
    TextView tvConsigneeAddress;
    @BindView(R2.id.tv_is_pick_ip_address)
    TextView tvIsPickIpAddress;
    @BindView(R2.id.iv_arrow_to_address_list)
    ImageView ivArrowToAddressList;
    @BindView(R2.id.ll_add_address)
    LinearLayout llAddAddress;
    @BindView(R2.id.ll_no_add_address)
    LinearLayout llNoAddAddress;
    @BindView(R2.id.tv_line_three)
    TextView tvLineThree;
    @BindView(R2.id.tv_delivery_method)
    TextView tvDeliveryMethod;
    @BindView(R2.id.tv_send_price)
    TextView tvSendPrice;
    @BindView(R2.id.iv_remind_list)
    ImageView ivRemindList;
    @BindView(R2.id.send_price_layout)
    LinearLayout llSendPriceDialog;
    @BindView(R2.id.tv_goods_price)
    TextView tvGoodsPrice;
    @BindView(R2.id.tv_coupon_price)
    TextView tvCouponPrice;
    @BindView(R2.id.iv_coupon_arrow_right)
    ImageView ivCouponArrowRight;
    @BindView(R2.id.ll_coupon_dialog)
    LinearLayout llCouponDialog;
    @BindView(R2.id.tv_red_package_price)
    TextView tvRedPackagePrice;
    @BindView(R2.id.cb_red_package)
    CheckBox cbRedPackage;
    @BindView(R2.id.ll_user_red_package)
    LinearLayout llUserRedPackage;
    @BindView(R2.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R2.id.commit_order_recyclerView)
    RecyclerView commitOrderRecyclerView;
    @BindView(R2.id.nestScoreView)
    NestedScrollView nestScoreView;
    @BindView(R2.id.view_line_four)
    TextView viewLineFour;
    @BindView(R2.id.tv_show_address)
    TextView tvShowAddress;
    @BindView(R2.id.ll_show_address)
    LinearLayout llShowAddress;
    @BindView(R2.id.tv_commit_price)
    TextView tvCommitPrice;
    @BindView(R2.id.tv_to_buy)
    TextView tvToBuy;
    @BindView(R2.id.view_line_two)
    TextView viewLineTwo;
    @BindView(R2.id.ll_coupon_line)
    View llCouponLine;

    @BindView(R2.id.card_order_shop_name_tv)
    TextView cardOrderShopNameTv;
    @BindView(R2.id.tv_cardbag_order_title)
    TextView tv_cardbag_order_title;
    @BindView(R2.id.tv_cardbag_order_discount_price)
    TextView tv_cardbag_order_discount_price;
    @BindView(R2.id.tv_cardbag_order_price)
    TextView tv_cardbag_order_price;
    @BindView(R2.id.card_goods_num_tv)
    TextView card_goods_num_tv;
    @BindView(R2.id.card_goods_sku_name)
    TextView card_goods_sku_name;
    @BindView(R2.id.iv_cardbag_order_card)
    ImageView ivCardbagOrderCard;
    @BindView(R2.id.card_order_shop_layout)
    LinearLayout card_order_shop_layout;
    @BindView(R2.id.order_head_address_layout)
    LinearLayout order_head_address_layout;
    @BindView(R2.id.order_send_type_layout)
    LinearLayout order_send_type_layout;
    @BindView(R2.id.card_order_title_line_layout)
    LinearLayout card_order_title_line_layout;
    @BindView(R2.id.tv_cardbag_order_phone)
    TextView tv_cardbag_order_phone;
    @BindView(R2.id.tv_cardbag_order_change)
    TextView tv_cardbag_order_change;
    @BindView(R2.id.tv_consignee_distance)
    TextView tv_consignee_distance;
    @BindView(R2.id.tax_top_line)
    View taxTopLine;
    @BindView(R2.id.tax_price_tv)
    TextView taxPriceTv;
    @BindView(R2.id.tax_price_layout)
    LinearLayout taxPriceLayout;
    @BindView(R2.id.tax_bottom_line)
    View taxBottomLine;
    @BindView(R2.id.order_shop_card_coupon_layout)
    LinearLayout orderShopCardCouponLayout;
    @BindView(R2.id.order_shop_card_coupon_tv)
    TextView orderShopCardCouponTv;

    private ConfirmGoodsListAdapter confirmGoodsListAdapter;
    private int sendType;
    private ShopInfo shopInfo;
    private NewCommPayPopUp payPopUp;
    private BaseCommLocateInfo baseCommLocateInfo;
    private ShopSelfAddressInfo.EmbeddedBean selfAddressInfo;

    private String consigneeAddress;
    private String consigneeAddressId;
    private String consigneeName;
    private String consigneePhone;
    private String mentionId;
    private String mentionPhone;
    private List<BaseOrderCouponInfo> platformCoupons;
    private List<OrderCouponInfo.MerchantCouponsBean> merchantCoupons;
    private List<BaseAddressInfo> userAddressInfoList = new ArrayList<>();
    private String platformCouponId; //优惠卷ID
    private String shopCouponSubMoney; //店铺优惠金额
    private String platformCouponSubMoney; //平台优惠金额
    private String cityCode;
    private OrderPostageInfo postageInfo;
    private double sendPrice;
    private ShopSendPriceControl shopSendPriceControl;
    private int orderFrom = -1;
    private LoginBaseInfo loginBaseInfo;

    private boolean isShopDistributions = true; //检测店铺不支持配送区域
    private String mentionName;
    private TextView shopCouponTv;
    private int shopCouponPosition;
    private String shopCouponId;
    private int couponPosition;
    private String lat;
    private String lon;
    private String selfType;
    private static final int ORDER_CARD_FROM_TYPE = 0;

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_commit_order;
    }

    @Override
    protected NewConfirmPresenter createPresenter() {
        return new NewConfirmPresenter(this);
    }

    @Override
    protected void initView() {
        setImmersionBar(commitOrderToolbar);
        tvTitle.setText("确认下单");
        commitOrderRecyclerView.setNestedScrollingEnabled(false);
        nestScoreView.setVerticalScrollBarEnabled(false);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    @Override
    protected void initDatas() {
        registerWeChatApp();
        baseCommLocateInfo = BaseSpUtils.getInstance().getCurrentCommuity(this);
        getIntentData();
    }

    //获取Intent
    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        orderFrom = bundle.getInt("orderFrom", -1);
        shopInfo = JsonUtils.parseObject(bundle.getString("jsonOrderInfo"), ShopInfo.class);

        if (!Preconditions.isNullOrEmpty(shopInfo)) {
            sendType = shopInfo.getSendType();
            cityCode = shopInfo.getCityCode();
            showOrderTitle();
            handleOrderFrom(orderFrom);
            addScrollListener();
        }
    }

    private void showOrderTitle() {
        if (shopInfo.getBuyType() == 4) {
            tvToBuy.setText("确定兑换");
        }
    }

    /**
     * 订单来源
     *
     * @param orderFrom
     */
    private void handleOrderFrom(int orderFrom) {
        switch (orderFrom) {
            case ORDER_CARD_FROM_TYPE:
                SHelper.vis(card_order_shop_layout, card_order_title_line_layout);
                SHelper.gone(order_head_address_layout, order_send_type_layout, commitOrderRecyclerView, ivCouponArrowRight);
                showCardOrderGoodsInfo();
                showCardOrderPhone();
                handleGoodsDiscountPrice();
                getOrderCouponInfo();
                break;
            default:
                getOrderUserAddress();
                getOrderCouponInfo();
                loadBindGoodsAdapter();
        }
    }

    /**
     * 卡包支付来源商品
     */
    private void showCardOrderGoodsInfo() {
        cardOrderShopNameTv.setText(shopInfo.getShopList().get(0).getShopName());
        if (!Preconditions.isNullOrEmpty(shopInfo.getShopList().get(0).getGoodsList())) {
            GoodInfo goodInfo = shopInfo.getShopList().get(0).getGoodsList().get(0);
            BaseImageLoaderUtils.getInstance().loadDefaltImage(this, ivCardbagOrderCard, goodInfo.getImg());
            tv_cardbag_order_title.setText(goodInfo.getName());
            if (!Preconditions.isNullOrEmpty(goodInfo.getDisCountPrice())) {
                tv_cardbag_order_discount_price.setText(goodInfo.getDisCountPrice());
            } else {
                tv_cardbag_order_discount_price.setText(goodInfo.getPrice());
            }
            card_goods_num_tv.setText("x" + goodInfo.getNums());
            card_goods_sku_name.setText(goodInfo.getSkuName());
        }
    }

    /**
     * 卡包订单绑定手机号
     */
    private void showCardOrderPhone() {
        loginBaseInfo = BaseSpUtils.getInstance().getUserBaseInfo(this);
        if (!Preconditions.isNullOrEmpty(loginBaseInfo)) {
            if (!Preconditions.isNullOrEmpty(BaseSpUtils.getInstance().getCardPhone(this))) {
                tv_cardbag_order_phone.setText(BaseSpUtils.getInstance().getCardPhone(this));
            } else if (!Preconditions.isNullOrEmpty(loginBaseInfo.getMobi())) {
                tv_cardbag_order_phone.setText(loginBaseInfo.getMobi());
            } else {
                SHelper.gone(tv_cardbag_order_phone);
                SHelper.vis(tv_cardbag_order_change);
                tv_cardbag_order_change.setText("请输入手机号码");
            }
        }
    }

    private void loadBindGoodsAdapter() {
        LinearLayoutManager main_layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        commitOrderRecyclerView.setLayoutManager(main_layoutManager);
        main_layoutManager.setStackFromEnd(true);
        confirmGoodsListAdapter = new ConfirmGoodsListAdapter(R.layout.module_shopping_item_commit_order_recyclerview, shopInfo.getShopList());
        confirmGoodsListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        commitOrderRecyclerView.setAdapter(confirmGoodsListAdapter);
        confirmGoodsListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.order_shop_coupon_layout) {
                shopCouponTv = (TextView) confirmGoodsListAdapter.getViewByPosition(commitOrderRecyclerView, position, R.id.order_shop_coupon_tv);
                shopCouponPosition = position;
                Intent intent = new Intent(NewConfirmOrderActivity.this, OrderCouponActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("jsonCouponInfo", JSON.toJSONString(merchantCoupons));
                bundle.putInt("couponFrom", 1);
                bundle.putInt("position", position);
                bundle.putInt("couponPosition", couponPosition);
                intent.putExtras(bundle);
                startActivityForResult(intent, OrderRequestConstant.REQUEST_ORDER_SHOP_COUPON_CODE);
            }
        });
        confirmGoodsListAdapter.setRxTextChangeListener((text, position) -> shopInfo.getShopList().get(position).setUserRemark(text));
    }

    /**
     * 处理平台优惠券、店铺优惠券价格
     */
    private void handleGoodsDiscountPrice() {
        if (!Preconditions.isNullOrEmpty(shopCouponSubMoney) && !Preconditions.isNullOrEmpty(platformCouponSubMoney)) {
            double shopAndPlatformMoney = NumberArithmeticUtils.add(ConverterUtils.toDouble(shopCouponSubMoney), ConverterUtils.toDouble(platformCouponSubMoney));
            showOrderPayPrice(NumberArithmeticUtils.sub(allPostagePrice(), shopAndPlatformMoney));
        } else if (!Preconditions.isNullOrEmpty(shopCouponSubMoney)) {
            showOrderPayPrice(NumberArithmeticUtils.sub(allPostagePrice(), ConverterUtils.toDouble(shopCouponSubMoney)));
        } else if (!Preconditions.isNullOrEmpty(platformCouponSubMoney)) {
            showOrderPayPrice(NumberArithmeticUtils.sub(allPostagePrice(), ConverterUtils.toDouble(platformCouponSubMoney)));
        } else {
            showOrderPayPrice(allPostagePrice());
        }
    }

    /**
     * 显示订单、支付价格
     *
     * @param payAmountPrice
     */
    private void showOrderPayPrice(double payAmountPrice) {
        String payPrice = CharacterUtils.isInteger(payAmountPrice) ? NumberArithmeticUtils.doubleToStr(payAmountPrice) : NumberArithmeticUtils.doubleToStr(0);
        if (shopInfo.getBuyType() != 4) {
            tvGoodsPrice.setText(AppConstants.MONEY + NumberArithmeticUtils.doubleToStr(getGoodsPrice()));
            tvAllPrice.setText(AppConstants.MONEY + payPrice);
            tvCommitPrice.setText(AppConstants.MONEY + payPrice);
        } else {
            tvGoodsPrice.setText(NumberArithmeticUtils.doubleToStr(getGoodsPrice()) + getString(R.string.confirm_order_inegral));
            tvAllPrice.setText(payPrice + getString(R.string.confirm_order_inegral));
            tvCommitPrice.setText(payPrice + getString(R.string.confirm_order_inegral));
        }
        if (!Preconditions.isNullOrEmpty(payPopUp)) {
            payPopUp.setPayPrice(payPrice);
        } else {
            payPopUp = new NewCommPayPopUp(this, payPrice, OrderPayFormType.PAY_FORM_TYPE_1.getPayFormType());
        }
    }


    /**
     * 处理邮费规则
     *
     * @param goodsPostageInfo
     */
    private void handleGoodsPostage(OrderPostageInfo goodsPostageInfo) {
        postageInfo = goodsPostageInfo;
        if (!Preconditions.isNullOrEmpty(postageInfo) && !Preconditions.isNullOrEmpty(postageInfo.getFeeList())) {
            handleGoodsDiscountPrice();
            for (OrderPostageInfo.FeeListBean basePostageInfo : postageInfo.getFeeList()) {
                calculateGoodsPostageShow(basePostageInfo);
            }
        }
    }

    /**
     * 显示邮费价格
     *
     * @param basePostageInfo
     */
    private void calculateGoodsPostageShow(OrderPostageInfo.FeeListBean basePostageInfo) {
        if (!Preconditions.isNullOrEmpty(basePostageInfo.getShippingFee()) && ConverterUtils.toDouble(basePostageInfo.getShippingFee()) > 0.00) {
            SHelper.vis(ivRemindList);
            sendPrice = basePostageInfo.getShippingFee();
            tvSendPrice.setText("¥" + ConverterUtils.toString(basePostageInfo.getShippingFee()));
        } else {
            tvSendPrice.setText("免配送费");
        }
    }

    /**
     * 计算邮费价格
     *
     * @return
     */
    private double allPostagePrice() {
        return getPostagePrice();
    }

    /**
     * 计算商品店铺价格
     *
     * @return
     */
    private double getGoodsPrice() {
        double price = 0;
        for (ShopListInfo shopItemInfo : shopInfo.getShopList()) {
            for (GoodInfo goodInfo : shopItemInfo.getGoodsList()) {
                if (!Preconditions.isNullOrEmpty(goodInfo.getDisCountPrice())) {
                    price += ConverterUtils.toDouble(goodInfo.getDisCountPrice()) * goodInfo.getNums();
                } else {
                    price += ConverterUtils.toDouble(goodInfo.getPrice()) * goodInfo.getNums();
                }
            }
        }
        return price;
    }


    /**
     * 包含邮费价格
     *
     * @return
     */
    private double getPostagePrice() {
        if (!Preconditions.isNullOrEmpty(postageInfo) && !Preconditions.isNullOrEmpty(postageInfo.getFeeList())) {
            for (OrderPostageInfo.FeeListBean basePostageInfo : postageInfo.getFeeList()) {
                return NumberArithmeticUtils.add(ConverterUtils.toDouble(basePostageInfo.getShippingFee()), getGoodsPrice());
            }
        }
        return getGoodsPrice();
    }

    /**
     * 获取是否支持配送地址
     */
    private void isCheckShopDistributions(String cityCode) {
        new GetShopDistributionTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                ShopListInfo shopInfo = (ShopListInfo) o;
                if (!Preconditions.isNullOrEmpty(shopInfo) && !Preconditions.isNullOrEmpty(shopInfo.getShopName())) {
                    isShopDistributions = false;
                } else {
                    isShopDistributions = true;
                }
            }
        }).execute(shopIdStr(), cityCode);
    }

    /**
     * 订单优惠券
     */
    private void getOrderCouponInfo() {
        //积分兑换不使用优惠券
        if (shopInfo.getBuyType() != 4) {
            mPresenter.getOrderPlatformAndShopCouponInfo(mPresenter.getOrderPlatformAndShopCouponParam(shopInfo));
        } else {
            SHelper.gone(llCouponDialog, llCouponLine);
        }
    }

    /**
     * 获取用户地址
     */
    private void getOrderUserAddress() {
        new GetAddressListTask(this, o -> {
            UserAddressInfo userAddressInfo = (UserAddressInfo) o;
            if (!Preconditions.isNullOrEmpty(userAddressInfo) && !Preconditions.isNullOrEmpty(userAddressInfo.get_embedded().getContent())) {
                UserAddressInfo.EmbeddedBean userAddressInfoEmbedded = userAddressInfo.get_embedded();
                if (!Preconditions.isNullOrEmpty(userAddressInfoEmbedded)) {
                    handleUserAddress(userAddressInfoEmbedded);
                }
            } else {
                noUserDefaultAddress();
                handleOrderSendType(shopInfo.getSendType());
            }
        }).execute();
    }

    /**
     * 处理收货地址
     *
     * @param selfAddressInfo
     */
    private void handleConsigneeShowUI(ShopSelfAddressInfo.EmbeddedBean selfAddressInfo) {
        for (ShopSelfAddressInfo.EmbeddedBean.ContentBean contentBean : selfAddressInfo.getContent()) {
            mentionName = contentBean.getName();
            mentionId = contentBean.getId();
            mentionPhone = contentBean.getContact_tel();
            cityCode = contentBean.getCityCode();
            handleAddressShowUI("", "", contentBean.getAddress(), contentBean.getName(), contentBean.getContact_tel(), contentBean.getDistance(), false);
            break;
        }
    }

    /**
     * 根据配送类型、收货地址经纬度、不同商品指定自提点、获取不同自提点列表
     *
     * @param userAddressInfoEmbedded
     */
    private void getNearPointAddress(UserAddressInfo.EmbeddedBean userAddressInfoEmbedded) {
        for (BaseAddressInfo userAddressInfo : getUserAddressInfo(userAddressInfoEmbedded.getContent())) {
            handleOrderFromPointAddress(userAddressInfo);
            break;
        }
    }

    /**
     * 处理订单来源自提点
     *
     * @param userAddressInfo
     */
    private void handleOrderFromPointAddress(BaseAddressInfo userAddressInfo) {

        switch (shopInfo.getGoodFrom()) {
            case 0:
                handleDownstairsShopSendType(userAddressInfo);
                break;
            case 1:
                handleGoodsSendType(userAddressInfo);
                break;
        }

    }

    /**
     * 处理楼下小店配送类似地址
     *
     * @param userAddressInfo
     */
    private void handleDownstairsShopSendType(BaseAddressInfo userAddressInfo) {


        handleOrderSendType(shopInfo.getSendType());

        //配送+自提
        if (sendType == SendTypeEnum.RECODE_0.getSendType()) {
            getShopSelfAddress(shopIdStr(), userAddressInfo.getLatitude(), userAddressInfo.getLongitude(), userAddressInfo, "4");
        }

        //仅自提
        if (sendType == SendTypeEnum.RECODE_2.getSendType()) {
            llAddAddress.setEnabled(false);
            SHelper.gone(ivArrowToAddressList);
            getShopSelfAddress(shopIdStr(), baseCommLocateInfo.lat, baseCommLocateInfo.lon, userAddressInfo, "3");
        }
    }

    /**
     * 处理电商配送类型地址
     *
     * @param userAddressInfo
     */
    private void handleGoodsSendType(BaseAddressInfo userAddressInfo) {

        handleOrderSendType(shopInfo.getSendType());


        //365商品
        if (shopInfo.getSource() == 3) {
            handleSelfAddressShowUI(null, userAddressInfo);
            SHelper.gone(tvIsPickIpAddress, taxTopLine);
            SHelper.vis(taxBottomLine, taxPriceLayout);
            return;
        }

        //自提商品
        if (!Preconditions.isNullOrEmpty(shopInfo.getPickupPoint())) {
            getShopSelfAddress(shopInfo.getPickupPoint(), baseCommLocateInfo.lat, baseCommLocateInfo.lon, userAddressInfo, "2");
            return;
        }

        //配送+自提
        if (sendType == SendTypeEnum.RECODE_0.getSendType()) {
            getShopSelfAddress(shopIdStr(), baseCommLocateInfo.lat, baseCommLocateInfo.lon, userAddressInfo, "1");
        }

        //自提
        if (sendType == SendTypeEnum.RECODE_2.getSendType()) {
            llAddAddress.setEnabled(false);
            SHelper.gone(ivArrowToAddressList);
            getShopSelfAddress(shopIdStr(), baseCommLocateInfo.lat, baseCommLocateInfo.lon, userAddressInfo, "3");
        }

        //仅配送
        if (sendType == SendTypeEnum.RECODE_1.getSendType()) {
            handleSelfAddressShowUI(null, userAddressInfo);
            SHelper.gone(tvIsPickIpAddress, taxTopLine);
        }
    }


    /**
     * 拼接多个店铺ID
     *
     * @return
     */
    private String shopIdStr() {
        StringBuilder builder = new StringBuilder();
        for (ShopListInfo shopInfo : shopInfo.getShopList()) {
            builder.append(shopInfo.getShopId());
            builder.append(",");
        }
        if (!Preconditions.isNullOrEmpty(builder)) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    /**
     * 根据店铺ID、当前经纬度、获取指定商品自提点
     *
     * @param lat
     * @param lon
     * @param userAddressInfo
     */
    private void getShopSelfAddress(String shopId, String lat, String lon, BaseAddressInfo userAddressInfo, String type) {
        setSelfAddressInfo(lat, lon, type);
        new GetShopSelfAddressTask(this, o -> {
            ShopSelfAddressInfo shopSelfAddressInfo = (ShopSelfAddressInfo) o;
            handleSelfAddressShowUI(shopSelfAddressInfo, userAddressInfo);
        }).execute(shopId, lon, lat, type, "");
    }

    /**
     * 自提点 经纬度、
     *
     * @param lat
     * @param lon
     * @param type
     */
    private void setSelfAddressInfo(String lat, String lon, String type) {
        this.lat = lat;
        this.lon = lon;
        this.selfType = type;
    }

    /**
     * status (integer, optional): 状态(0正常 -1删除,默认正常:0)
     *
     * @param contentBeans
     * @return
     */
    private List<BaseAddressInfo> getUserAddressInfo(List<BaseAddressInfo> contentBeans) {
        for (BaseAddressInfo contentInfo : contentBeans) {
            filterUserAddressList(contentInfo);
        }
        return userAddressInfoList;
    }

    /**
     * 过滤用户收货地址
     *
     * @param contentInfo
     */
    private void filterUserAddressList(BaseAddressInfo contentInfo) {
        if (contentInfo.getStatus() == 0) {
            BaseAddressInfo contentBean = new BaseAddressInfo();
            contentBean.setId(contentInfo.getId());
            contentBean.setServiceData(contentInfo.getServiceData());
            contentBean.setAddress(contentInfo.getAddress() + contentInfo.getAddressDetails());
            contentBean.setIsDefault(contentInfo.getIsDefault());
            contentBean.setLatitude(contentInfo.getLatitude());
            contentBean.setLongitude(contentInfo.getLongitude());
            contentBean.setName(contentInfo.getName());
            contentBean.setCityCode(contentInfo.getCityCode());
            contentBean.setPhone(contentInfo.getPhone());
            userAddressInfoList.add(contentBean);
        }
    }

    /**
     * 用户默认收货地址
     */
    private void handleUserAddress(UserAddressInfo.EmbeddedBean userAddressInfoEmbedded) {
        if (!Preconditions.isNullOrEmpty(userAddressInfoEmbedded.getContent())) {
            Collections.reverse(userAddressInfoEmbedded.getContent());
            getNearPointAddress(userAddressInfoEmbedded);
        }
    }

    /**
     * 没有默认用户地址跳转添加
     */
    private void noUserDefaultAddress() {
        SHelper.gone(llAddAddress, viewLineTwo);
        SHelper.vis(llNoAddAddress, tvLineThree);
        tvDeliveryMethod.setText("快递");
        Intent intent = new Intent(NewConfirmOrderActivity.this, AddAddressActivity.class);
        startActivityForResult(intent, OrderRequestConstant.REQUEST_ADD_ADDRESS_CODE);
    }

    /**
     * 收货地址显示
     *
     * @param shopSelfAddressInfo
     */
    private void handleSelfAddressShowUI(ShopSelfAddressInfo shopSelfAddressInfo, BaseAddressInfo userAddressInfo) {
        if (!Preconditions.isNullOrEmpty(shopSelfAddressInfo) && !Preconditions.isNullOrEmpty(shopSelfAddressInfo.get_embedded().getContent())) {
            selfAddressInfo = shopSelfAddressInfo.get_embedded();
            handleConsigneeShowUI(selfAddressInfo);
        } else {
            cityCode = userAddressInfo.getCityCode();
            handleAddressShowUI(cityCode, userAddressInfo.getServiceData(), userAddressInfo.getAddress(), userAddressInfo.getName(), userAddressInfo.getPhone(), "", true);
        }
    }

    /**
     * 处理显示自提地址和用户地址
     *
     * @param address
     */
    private void handleAddressShowUI(String cityCode, String addressId, String address, String name, String tel, String distance, boolean isUserSelf) {
        SHelper.gone(llNoAddAddress, tvLineThree);
        SHelper.vis(llAddAddress, viewLineTwo);
        if (isUserSelf) {
            showUserConsigneeMsg(addressId, address, name, tel);
            handleOrderSendType(shopInfo.getSendType());
            isCheckShopDistributions(cityCode);
        } else {
            showPointConsigneeMsg(address);
            showNearPointAddress(address, name, tel, distance);
            handleOrderSendType(shopInfo.getSendType());
        }
    }

    /**
     * 显示用户收货地址
     *
     * @param address
     * @param name
     * @param tel
     */
    private void showUserConsigneeMsg(String addressId, String address, String name, String tel) {
        copyUserAddress(addressId, address, name, tel);
        tvConsigneeAddress.setText(address);
        ivAddressType.setBackgroundResource(R.mipmap.ic_location_small);
        SHelper.gone(tvRecommendPost, tv_consignee_distance);
        SHelper.gone(tvIsPickIpAddress);
        tvDeliveryMethod.setText("快递");
        shopInfo.setSendType(1);
    }

    /**
     * 附近自提点地址
     *
     * @param address
     * @param name
     * @param tel
     */
    private void showNearPointAddress(String address, String name, String tel, String distance) {
        String pointName = Preconditions.isNullOrEmpty(name) ? "" : "（" + name + "）";
        String pointTel = Preconditions.isNullOrEmpty(tel) ? "" : "（" + tel + "）";
        RxTextTool.getBuilder("").append("[推荐自提]").setForegroundColor(getResources().getColor(R.color.home_red)).append(address + pointName + pointTel).into(tvConsigneeAddress);
        tvDeliveryMethod.setText("自提");
        tvSendPrice.setText("免配送费");
        shopInfo.setSendType(2);
        showPointAddressDistance(distance);
        SHelper.gone(ivRemindList, tvIsPickIpAddress);
        SHelper.vis(tvRecommendPost, tv_consignee_distance);
    }

    /**
     * 获取自提点收货人信息
     *
     * @param address
     */
    private void showPointConsigneeMsg(String address) {
        copyUserAddress("", address, SpUtils.getInstance().getConsigneeName(this), SpUtils.getInstance().getConsigneePhone(this));
    }

    /**
     * 显示自提点距离
     *
     * @param distance
     */
    private void showPointAddressDistance(String distance) {
        if (ConverterUtils.toFloat(distance) < 1000) {
            tv_consignee_distance.setText("距" + CharacterUtils.regularizePrice(ConverterUtils.toFloat(distance)) + "m");
        } else {
            String dis = CharacterUtils.regularizePrice(ConverterUtils.toFloat(distance) / 1000);
            tv_consignee_distance.setText("距" + dis + "km");
        }
    }

    /**
     * 赋值用户地址信息
     *
     * @param address
     * @param name
     * @param phone
     */
    private void copyUserAddress(String addressId, String address, String name, String phone) {
        this.consigneeAddressId = addressId;
        this.consigneeAddress = address;
        this.consigneeName = name;
        this.consigneePhone = phone;
        showPointConsigneeMsg(name, phone);
    }

    /**
     * 订单配送方式
     *
     * @param sendType
     */
    private void handleOrderSendType(int sendType) {
        switch (sendType) {
            case 0:
                getPostageInfo();
                handleGoodsDiscountPrice();
                break;
            case 1:
                getPostageInfo();
                handleGoodsDiscountPrice();
                break;
            case 2:
                getPostageInfo();
                handleGoodsDiscountPrice();
                break;
        }
    }

    /**
     * 获取邮费
     */
    private void getPostageInfo() {
        mPresenter.orderPostage(mPresenter.getCreateConfirmOrderPostageData(shopInfo, consigneeAddressId, consigneeAddress, consigneeName, consigneePhone, platformCouponId, cityCode, sendPrice, mentionId, mentionName, mentionPhone));
    }

    /**
     * 显示自提收货人信息
     *
     * @param name
     * @param phone
     */
    private void showPointConsigneeMsg(String name, String phone) {
        tvConsigneeName.setText(name);
        tvConsigneePhone.setText(phone);
    }

    /**
     * 创建订单
     *
     * @param v
     */
    private void createConfirmOrder(View v) {
        if (isShopDistributions) {
            mPresenter.submitOrder(mPresenter.getCreateConfirmOrderData(shopInfo, consigneeAddressId, consigneeAddress, consigneeName, consigneePhone, platformCouponId, cityCode, sendPrice, mentionId, mentionName, mentionPhone), v);
        } else {
            WpToast.l(this, "不支持当前选择配送区域！");
        }
    }

    @Override
    public void showSubmitOrderResult(SubmitOrderResultBean resultBean, View v) {
        if (shopInfo.getBuyType() != 4) {
            showPayPop(resultBean);
        } else {
            payPopUp.setConfirmPayOrder(resultBean);
            payPopUp.addShopInfo(shopInfo);
            payPopUp.selectedConfirmPayWay(resultBean.getBigOrder(), "integralPay", 4);
        }
        rxBusToShopCart();
    }

    @Override
    public void showOrderPostageResult(OrderPostageInfo orderPostageInfo) {
        handleGoodsPostage(orderPostageInfo);
    }

    private void rxBusToShopCart() {
        ToCartRefreshEvent toCartRefreshEvent = new ToCartRefreshEvent();
        toCartRefreshEvent.setShopCartRefresh(true);
        RxBus.getInstance().post(toCartRefreshEvent);
    }

    @Override
    public void showOrderPlatformAndShopCouponInfo(OrderCouponInfo orderCouponInfo) {
        if (!Preconditions.isNullOrEmpty(orderCouponInfo)) {
            if (!Preconditions.isNullOrEmpty(orderCouponInfo.getPlatformCoupons())) {
                SHelper.vis(ivCouponArrowRight);
                platformCoupons = orderCouponInfo.getPlatformCoupons();
                loadPlatformCouponsInfo(true);
                llCouponDialog.setEnabled(true);
            } else {
                SHelper.gone(ivCouponArrowRight);
                tvCouponPrice.setText("无可用优惠券");
                llCouponDialog.setEnabled(false);
            }

            handleCardShopCoupon(orderCouponInfo);

        }
    }

    /**
     * 处理卡多多、电商店铺优惠券
     *
     * @param orderCouponInfo
     */
    private void handleCardShopCoupon(OrderCouponInfo orderCouponInfo) {
        if (orderFrom == ORDER_CARD_FROM_TYPE) {
            if (!Preconditions.isNullOrEmpty(orderCouponInfo.getMerchantCoupons()) && !Preconditions.isNullOrEmpty(orderCouponInfo.getMerchantCoupons().get(0).getCouponList())) {
                merchantCoupons = orderCouponInfo.getMerchantCoupons();
                SHelper.vis(orderShopCardCouponLayout);
                orderShopCardCouponTv.setText("-" + AppConstants.MONEY + CharacterUtils.roundByScale(ConverterUtils.toDouble(orderCouponInfo.getMerchantCoupons().get(0).getCouponList().get(0).getSubMoney())) + "(" + orderCouponInfo.getMerchantCoupons().get(0).getCouponList().get(0).getCouponName() + ")");
                loadMerchantCouponsInfo();
                handleGoodsDiscountPrice();
            }
        } else {
            if (!Preconditions.isNullOrEmpty(orderCouponInfo.getMerchantCoupons())) {
                merchantCoupons = orderCouponInfo.getMerchantCoupons();
                confirmGoodsListAdapter.addOrderMerchantCoupons(orderCouponInfo.getMerchantCoupons());
                loadMerchantCouponsInfo();
                handleGoodsDiscountPrice();
            }
        }
    }

    @Override
    public void showOrderPlatformCouponInfo(List<BaseOrderCouponInfo> orderCouponInfo) {
        if (!Preconditions.isNullOrEmpty(orderCouponInfo)) {
            platformCoupons = orderCouponInfo;
            loadPlatformCouponsInfo(true);
        }
    }

    /**
     * 加载平台优惠卷
     */
    private void loadPlatformCouponsInfo(boolean isUseCoupon) {
        for (BaseOrderCouponInfo couponItem : platformCoupons) {
            platformCouponId = couponItem.getId();
            showPlatformCouponPrice(isUseCoupon, couponItem.getSubMoney(), couponItem.getCouponName());
            handleGoodsDiscountPrice();
            break;
        }
    }

    /**
     * 加载店铺优惠卷
     */
    private void loadMerchantCouponsInfo() {
        double amountPrice = 0;
        for (OrderCouponInfo.MerchantCouponsBean merchantInfo : merchantCoupons) {
            for (ShopListInfo shopInfo : shopInfo.getShopList()) {
                if (merchantInfo.getShopId().equals(shopInfo.getShopId())) {
                    if (!Preconditions.isNullOrEmpty(merchantInfo.getCouponList())) {
                        BaseOrderCouponInfo baseOrderCouponInfo = merchantInfo.getCouponList().get(0);
                        merchantInfo.getCouponList().get(0).setChanged("Y");
                        shopCouponId = baseOrderCouponInfo.getId();
                        amountPrice += ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney());
                        shopCouponSubMoney = ConverterUtils.toString(amountPrice);
                        shopInfo.setCouponId(shopCouponId);
                        shopInfo.setCouponSubMoney(shopCouponSubMoney);
                    }
                }
            }
        }
    }

    /**
     * 显示平台优惠价格
     *
     * @param isUseCoupon 是否使用优惠卷
     */
    private void showPlatformCouponPrice(boolean isUseCoupon, String subMoney, String couponName) {
        platformCouponSubMoney = subMoney;
        if (isUseCoupon && !Preconditions.isNullOrEmpty(subMoney)) {
            tvCouponPrice.setText("- ¥" + CharacterUtils.roundByScale(ConverterUtils.toDouble(subMoney)) + "(" + couponName + ")");
            llCouponDialog.setEnabled(true);
        } else {
            SHelper.vis(ivCouponArrowRight);
            llCouponDialog.setEnabled(true);
            tvCouponPrice.setText("未使用平台优惠卷");
        }
    }

    /**
     * 显示店铺优惠券
     *
     * @param subMoney
     * @param couponName
     */
    private void showShopCouponPrice(String subMoney, String couponName, String shopCouponId, int couponPosition) {
        if (!Preconditions.isNullOrEmpty(subMoney)) {
            for (BaseOrderCouponInfo baseOrderCouponInfo : merchantCoupons.get(shopCouponPosition).getCouponList()) {
                if (shopCouponId.equals(baseOrderCouponInfo.getId())) {
                    baseOrderCouponInfo.setChanged("Y");
                    if (orderFrom == ORDER_CARD_FROM_TYPE) {
                        showShopCouponPrice(orderShopCardCouponTv, subMoney, couponName);
                    } else {
                        showShopCouponPrice(shopCouponTv, subMoney, couponName);
                    }
                    loadMerchantShopCouponsInfo(couponPosition, shopCouponId);
                    mPresenter.getOrderPlatformCouponInfo(mPresenter.getOrderPlatformCouponParam(shopInfo));
                } else {
                    baseOrderCouponInfo.setChanged("N");
                }
            }
        } else {
            merchantCoupons.get(shopCouponPosition).getCouponList().get(couponPosition).setChanged("N");
            if (orderFrom == ORDER_CARD_FROM_TYPE) {
                orderShopCardCouponLayout.setEnabled(true);
                orderShopCardCouponTv.setText("未使用店铺优惠卷");
            } else {
                shopCouponTv.setEnabled(true);
                shopCouponTv.setText("未使用店铺优惠卷");
            }
            loadMerchantShopCouponsInfo(couponPosition, shopCouponId);
            mPresenter.getOrderPlatformCouponInfo(mPresenter.getOrderPlatformCouponParam(shopInfo));
        }
        handleGoodsDiscountPrice();
    }

    /**
     * 显示店铺优惠价格
     *
     * @param tv
     * @param subMoney
     * @param couponName
     */
    private void showShopCouponPrice(TextView tv, String subMoney, String couponName) {
        tv.setText("- ¥" + CharacterUtils.roundByScale(ConverterUtils.toDouble(subMoney)) + "(" + couponName + ")");
    }

    /**
     * 不同店铺选中优惠券
     */
    private void loadMerchantShopCouponsInfo(int couponPosition, String shopCouponId) {
        BaseOrderCouponInfo baseOrderCouponInfo = merchantCoupons.get(shopCouponPosition).getCouponList().get(couponPosition);
        if ("Y".equals(baseOrderCouponInfo.getChanged())) {
            if (shopCouponId.equals(baseOrderCouponInfo.getId())) {
                if (!Preconditions.isNullOrEmpty(shopCouponSubMoney) && isCouponSubMoneyNumber(baseOrderCouponInfo)) {
                    shopCouponSubMoney = baseOrderCouponInfo.getSubMoney();
                } else {
                    shopCouponSubMoney = ConverterUtils.toString(NumberArithmeticUtils.add(ConverterUtils.toDouble(shopCouponSubMoney), ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney())));
                }
            } else {
                shopCouponSubMoney = ConverterUtils.toString(NumberArithmeticUtils.add(ConverterUtils.toDouble(shopCouponSubMoney), ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney())));
            }
            setShopCouponPosition(shopCouponPosition, baseOrderCouponInfo.getId(), shopCouponSubMoney);
        } else {
            if (!Preconditions.isNullOrEmpty(shopCouponSubMoney) && isCouponSubMoneyNumber(baseOrderCouponInfo)) {
                shopCouponSubMoney = isNumber(baseOrderCouponInfo) ? ConverterUtils.toString(NumberArithmeticUtils.sub(ConverterUtils.toDouble(shopCouponSubMoney), ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney()))) : "";
            }
            setShopCouponPosition(shopCouponPosition, "", "");
        }
    }

    /**
     * 设置店铺优惠参数
     *
     * @param shopCouponPosition
     * @param shopCouponId
     * @param shopCouponSubMoney
     */
    private void setShopCouponPosition(int shopCouponPosition, String shopCouponId, String shopCouponSubMoney) {
        shopInfo.getShopList().get(shopCouponPosition).setCouponId(shopCouponId);
        shopInfo.getShopList().get(shopCouponPosition).setCouponSubMoney(shopCouponSubMoney);
    }

    /**
     * 店铺优惠价格是否整数
     *
     * @param baseOrderCouponInfo
     * @return
     */
    private boolean isCouponSubMoneyNumber(BaseOrderCouponInfo baseOrderCouponInfo) {
        if (ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断计算价格是否整数
     *
     * @param baseOrderCouponInfo
     * @return
     */
    private boolean isNumber(BaseOrderCouponInfo baseOrderCouponInfo) {
        if (NumberArithmeticUtils.sub(ConverterUtils.toDouble(shopCouponSubMoney), ConverterUtils.toDouble(baseOrderCouponInfo.getSubMoney())) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 支付弹框
     *
     * @param resultBean
     */
    private void showPayPop(SubmitOrderResultBean resultBean) {
        payPopUp.setConfirmPayOrder(resultBean);
        payPopUp.showAtLocation(tvTitle, Gravity.BOTTOM, 0, 0);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void addListener() {
        tvBack.setOnClickListener(v -> finish());

        RxView.clicks(tvToBuy)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        //卡包订单来源
                        if (orderFrom == ORDER_CARD_FROM_TYPE) {
                            if (!Preconditions.isNullOrEmpty(tv_cardbag_order_phone.getText().toString().trim())) {
                                consigneePhone = tv_cardbag_order_phone.getText().toString().trim();
                                createConfirmOrder(tvToBuy);
                            } else {
                                WpToast.l(NewConfirmOrderActivity.this, "请先更换手机号码");
                            }
                            return;
                        }

                        //普通订单来源
                        if (!Preconditions.isNullOrEmpty(tvConsigneeAddress.getText().toString().trim())) {
                            createConfirmOrder(tvToBuy);
                        } else {
                            WpToast.l(NewConfirmOrderActivity.this, "请选择收货地址");
                        }
                    }
                });

        llNoAddAddress.setOnClickListener(v -> {
            Intent intent = new Intent(NewConfirmOrderActivity.this, AddAddressActivity.class);
            startActivityForResult(intent, OrderRequestConstant.REQUEST_ADD_ADDRESS_CODE);
        });
        llAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewConfirmOrderActivity.this, ReceivingAddressListActivity.class);
                intent.putExtra("selfAddress", selfAddressInfo);
                if (!Preconditions.isNullOrEmpty(shopInfo.getPickupPoint())) {
                    intent.putExtra("sendType", 2);
                } else {
                    intent.putExtra("sendType", sendType);
                }
                intent.putExtra("shopId", shopIdStr());
                intent.putExtra("goodFrom", shopInfo.getGoodFrom());
                intent.putExtra("source", shopInfo.getSource());
                intent.putExtra("lat", lat);
                intent.putExtra("lon", lon);
                intent.putExtra("selfType", selfType);
                startActivityForResult(intent, OrderRequestConstant.REQUEST_SELF_ADDRESS_CODE);
            }
        });

        llCouponDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewConfirmOrderActivity.this, OrderCouponActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("jsonCouponInfo", JSON.toJSONString(platformCoupons));
                bundle.putInt("couponFrom", 0);
                bundle.putString("platformCouponId", platformCouponId);
                intent.putExtras(bundle);
                startActivityForResult(intent, OrderRequestConstant.REQUEST_ORDER_PLA_COUPON_CODE);
            }
        });
        orderShopCardCouponLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewConfirmOrderActivity.this, OrderCouponActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("jsonCouponInfo", JSON.toJSONString(merchantCoupons));
                bundle.putInt("couponFrom", 1);
                bundle.putInt("couponPosition", couponPosition);
                intent.putExtras(bundle);
                startActivityForResult(intent, OrderRequestConstant.REQUEST_ORDER_SHOP_COUPON_CODE);
            }
        });

        ivRemindList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shopSendPriceControl = new ShopSendPriceControl(NewConfirmOrderActivity.this);
                shopSendPriceControl.addShopPostageInfo(postageInfo);
                shopSendPriceControl.showAtLocation(tvBack, Gravity.CENTER, 0, 0);
            }
        });

        tv_cardbag_order_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewConfirmOrderActivity.this, CardOrderPhoneActivity.class);
                startActivityForResult(intent, OrderRequestConstant.REQUEST_CARD_ORDER_PHONE_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OrderRequestConstant.REQUEST_SELF_ADDRESS_CODE && resultCode == RESULT_OK) {
            addressCallBackData(data);
        } else if (requestCode == OrderRequestConstant.REQUEST_SELF_ADDRESS_CODE && resultCode == RESULT_OK) {
            showPointConsigneeMsg(SpUtils.getInstance().getConsigneeName(this), SpUtils.getInstance().getConsigneePhone(this));
        } else if (requestCode == OrderRequestConstant.REQUEST_ADD_ADDRESS_CODE && resultCode == RESULT_OK) {
            addressCallBackData(data);
        } else if (requestCode == OrderRequestConstant.REQUEST_ORDER_PLA_COUPON_CODE && resultCode == RESULT_OK) {
            orderCouponBackData(data, true);
        } else if (requestCode == OrderRequestConstant.REQUEST_ORDER_SHOP_COUPON_CODE && resultCode == RESULT_OK) {
            orderCouponBackData(data, false);
        } else if (requestCode == OrderRequestConstant.REQUEST_ORDER_PLA_COUPON_CODE && resultCode == OrderRequestConstant.REQUEST_COUPON_CANCEL_RESULT_CODE) {
            orderCouponBackData(data, true);
        } else if (requestCode == OrderRequestConstant.REQUEST_ORDER_SHOP_COUPON_CODE && resultCode == OrderRequestConstant.REQUEST_COUPON_CANCEL_RESULT_CODE) {
            orderCouponBackData(data, false);
        } else if (requestCode == OrderRequestConstant.REQUEST_CARD_ORDER_PHONE_CODE && resultCode == RESULT_OK) {
            tv_cardbag_order_phone.setText(BaseSpUtils.getInstance().getCardPhone(this));
            SHelper.vis(tv_cardbag_order_phone);
            SHelper.gone(tv_cardbag_order_change);
        }
    }

    /**
     * 订单优惠卷
     *
     * @param data
     */
    private void orderCouponBackData(Intent data, boolean isPlatformCoupon) {
        String subMoney = data.getStringExtra("subMoney");
        String couponName = data.getStringExtra("couponName");
        if (isPlatformCoupon) {
            platformCouponId = data.getStringExtra("couponId");
            showPlatformCouponPrice(true, subMoney, couponName);
            handleGoodsDiscountPrice();
        } else {
            shopCouponId = data.getStringExtra("couponId");
            couponPosition = data.getIntExtra("couponPosition", 0);
            showShopCouponPrice(subMoney, couponName, shopCouponId, couponPosition);
        }
    }

    /**
     * 地址回调结果
     *
     * @param data
     */
    private void addressCallBackData(Intent data) {
        consigneeAddress = data.getStringExtra("address");
        mentionId = data.getStringExtra("mentionId");
        mentionName = data.getStringExtra("mentionName");
        mentionPhone = data.getStringExtra("tel");
        cityCode = data.getStringExtra("cityCode");
        String distance = data.getStringExtra("distance");
        String addressId = data.getStringExtra("addressId");
        boolean isUserSelf = data.getBooleanExtra("isSelf", true);
        handleAddressShowUI(cityCode, addressId, consigneeAddress, mentionName, mentionPhone, distance, isUserSelf);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void addScrollListener() {
        nestScoreView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > 200) {
                    if (!Preconditions.isNullOrEmpty(tvConsigneeAddress.getText().toString().trim())) {
                        SHelper.vis(llShowAddress);
                        tvShowAddress.setText("收货地址:" + tvConsigneeAddress.getText().toString().trim());
                    }
                } else {
                    SHelper.gone(llShowAddress);
                }
            }
        });
    }

    public void showPayLoading() {
        showLoading();
    }

    public void dismissPayLoading() {
        dismissLoading();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (payPopUp != null && payPopUp.isShowing()) {
            payPopUp.dismiss();
            payPopUp = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (payPopUp != null) {
            payPopUp.payPopUnregisterRx();
        }
    }
}
